﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web;

namespace Ttifa.WebApiBase
{
    /// <summary>
    /// 接口返回数据类型处理
    /// </summary>
    public class ApiContentNegotiator : IContentNegotiator
    {
        /// <summary>
        /// String返回头部标识
        /// </summary>
        private static readonly MediaTypeHeaderValue StringHeaderValue = new MediaTypeHeaderValue("text/plain");

        /// <summary>
        /// Json返回头部标识
        /// </summary>
        private static readonly MediaTypeHeaderValue JsonHeaderValue = new MediaTypeHeaderValue("application/json");

        /// <summary>
        /// Jsonp返回头部标识
        /// </summary>
        private static readonly MediaTypeHeaderValue JsonpHeaderValue = new MediaTypeHeaderValue("text/javascript");

        /// <summary>
        /// 响应数据处理
        /// </summary>
        /// <param name="type"></param>
        /// <param name="request"></param>
        /// <param name="formatters"></param>
        /// <returns></returns>
        public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)
        {
            if (request.Method == HttpMethod.Get)
            {
                string jsonp = request.GetQueryNameValuePairs().FirstOrDefault(p => p.Key.Trim().ToLower() == "jsonp").Value;

                if (!string.IsNullOrWhiteSpace(jsonp))
                    return new ContentNegotiationResult(new JsonpMediaTypeFormatter(jsonp), JsonpHeaderValue); // Jsonp
            }

            if (type.IsClass && type != typeof(string))
                return new ContentNegotiationResult(new JsonpMediaTypeFormatter(), JsonHeaderValue); // Json

            return new ContentNegotiationResult(new StringMediaTypeFormatter(), StringHeaderValue); // String
        }
    }
}